package loginbean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

@SuppressWarnings({ "rawtypes", "serial" })
public class ObjectMap extends java.util.HashMap
{
	@SuppressWarnings("unchecked")
	public ObjectMap(int tenantid)
	{
		Connection conn = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "mydb";
		String driver = "com.mysql.jdbc.Driver";
		String userName = "root"; 
		String password = "";
		String strQuery = ""; 
		Statement st = null;
		ResultSet rs = null;
		try 
		{
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(url+dbName,userName,password);
			strQuery = "select o.objectid, objectname, fieldid, fieldname, datatype from objecttable o, fieldtable f "
					 + "where f.objectid=o.objectid and tenantid=" + tenantid;
			st = conn.createStatement();
			rs = st.executeQuery(strQuery);
			ObjectBean obj = null;
			FieldBean field = null;
			ArrayList<FieldBean> ar = new ArrayList<FieldBean>();
			String objectId = null, tempId = null;
			while(rs.next())
			{
				/* This list is sorted by object id's.  It has as many rows as there are fields.
				 * First we will need to create an object, then start populating fields. */
				tempId = objectId;
				objectId = rs.getString(1);			
				if(!objectId.equals(tempId))
				{
					if(obj != null)
					{	
						//write to the hash map
						FieldBean[] fields = new FieldBean[ar.size()];
						for(int i=0; i<ar.size(); i++)
						{
							fields[i] = ar.get(i);
						}
						obj.setFields(fields);
						this.put(tempId, obj);
					}
					obj = new ObjectBean();
					obj.setObjectId(new Integer(objectId).intValue());
					obj.setName(rs.getString(2));
					ar = new ArrayList<FieldBean>();
				}
	
				field = new FieldBean(rs.getString(4),rs.getString(5),new Integer(rs.getString(3)).intValue());
				ar.add(field);
			}
			FieldBean[] fields = new FieldBean[ar.size()];
			for(int i=0; i<ar.size(); i++)
			{
				fields[i] = ar.get(i);
			}
			obj.setFields(fields);
			this.put(objectId, obj);
			conn.close();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
}
